<template>
	<!-- 此代码应封装为组件使用 -->
	<view class="move-btn flex-1" :style="{'left': movex + 'px', 'top': movey + 'px'}" @touchmove="move" @touchend="end"
		@touchstart="start" :class="[isEnd&&'animation']">
		<text class="button-title">{{title}}</text>
	</view>
</template>

<script>
	export default {
		props: {
			title: {
				type: String,
				default: '我需要帮助'
			}
		},
		data() {
			return {
				movex: 0,
				movey: 0,
				domw: 0,
				domh: 0,
				screenW: 0,
				screenH: 0,
				isEnd: false
			}
		},
		created() {
			// 获取屏幕宽度
			let system = uni.getSystemInfoSync()
			this.screenW = system.windowWidth
			this.screenH = system.windowHeight
			// 初始位置
			this.movey = this.screenH - 60
			this.movex = this.screenW - 60

			setTimeout(() => {
				let page = this
				// 获取元素信息
				let query = uni.createSelectorQuery()
				let dom = query.select('.move-btn')
				dom.boundingClientRect(function(res) {
					page.domw = res.width
					page.domh = res.height
				}).exec()
			}, 1)
		},
		methods: {
			start() {
				this.isEnd = false
			},
			move(e) {
				let pageX = e.changedTouches[0].pageX
				let pageY = e.changedTouches[0].pageY
				this.isEnd = false
				let movex = pageX - (this.domw / 2) > 0 ? pageX - (this.domw / 2) : 0
				let movey = pageY - (this.domh / 2) > 0 ? pageY - (this.domw / 2) : 0

				this.movex = movex > this.screenW - this.domw ? this.screenW - this.domw : movex
				this.movey = movey > this.screenH - this.domh ? this.screenH - this.domh : movey
			},
			end(e) {
				let movex = e.changedTouches[0].pageX
				// 自动吸附屏幕边缘
				let halfScreen = this.screenW / 2
				let moveRes = halfScreen - movex
				// moveRes 正值吸附左边 负值吸附右边

				let page = this
				setTimeout(() => {
					page.isEnd = true
					page.movex = moveRes > 0 ? 0 : page.screenW - page.domw
				}, 1000)
			},
		}
	}
</script>

<style lang="scss">
	.move-btn {
		position: absolute;
		width: 52px;
		height: 52px;
		background-color: #FD5667;
		z-index: 999;
		border-radius: 50px;
		padding: 5px;
		box-sizing: border-box;

		.button-title {
			color: #FFF;
			font-size: 12px;
			text-align: center;
		}
	}

	.animation {
		transition: all .3s;
		opacity: .5;
	}
</style>